package com.dycong.common.IO.calculator.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO�����Դ��__α�첽I/O
 *
 * @author yangtao__anxpp.com
 * @version 1.0
 */
public final class ServerBetter {

    private static int DEFAULT_PORT = 12345;

    private static ServerSocket server;

    private static ExecutorService executorService = Executors.newFixedThreadPool(60);

    public static void start() throws IOException {

        start(DEFAULT_PORT);
    }

    public synchronized static void start(int port) throws IOException {
        if (server != null) return;
        try {

            server = new ServerSocket(port);
            System.out.println("server listening port: " + port);
            Socket socket;

            while (true) {
                socket = server.accept();
                executorService.execute(new ServerWriter(socket));      //todo 开启服务端监听控制台输入并循环out.write()线程
                executorService.execute(new ServerReader(socket));      //todo 开启服务端监听Client消息循环in.read()线程
            }
        } finally {
            if (server != null) {
                server.close();
                server = null;
            }
        }
    }
}